﻿using System;
using Microsoft.Xna.Framework;
using PoolGame2.Assets;
namespace PoolGame2.Physics
{
    class BallBallCollision : Collision
    {

        public BallBallCollision(Ball a, Ball b, float collideTime)
        {
            this.a = a;
            this.b = b;
            this.collisionTime = collideTime;
        }

        public BallBallCollision(Ball a, Ball b, float collideTime, int val)
            : this(a, b, collideTime)
        {
            this.value = val;
        }

        public override void ResolveCollision(bool playSound)
        {
            if (a.velocity != Vector3.Zero || b.velocity != Vector3.Zero)
            {
                // ensure that the balls are not interpenetrating
                float distance = Vector3.DistanceSquared(a.getPosition(), b.getPosition());

                float diff = PhysicsConstants.DEFAULT_RADIUS_SQUARED * 2 - distance;
                if (diff > 0)
                {
                    // diff needs to be sqrt'ed here
                    diff = (float)Math.Sqrt(diff);
                    // try and move the balls correctly
                    a.setPosition(a.getPosition() - a.getVelocity() * diff);
                    b.setPosition(b.getPosition() - b.getVelocity() * diff);
                    //return false;
                }

                Vector3 collisionNormal = a.getPosition() - b.getPosition();
                Vector3.Normalize(ref collisionNormal, out collisionNormal);

                // linear transfer
                Vector3 an = Vector3.Dot(a.velocity, -collisionNormal) * -collisionNormal;
                Vector3 bn = Vector3.Dot(b.velocity, collisionNormal) * collisionNormal;

                Vector3 at = a.velocity - an;
                Vector3 bt = b.velocity - bn;

                // conservation of linear momentum
                a.velocity = (at + bn);
                b.velocity = (bt + an);

                a.velocity *= PhysicsConstants.BALL_BALL_ELASTICITY_COEFFICIANT;
                b.velocity *= PhysicsConstants.BALL_BALL_ELASTICITY_COEFFICIANT;

                if (playSound)
                {
                    PoolGame.audioDBManger.PlaySoundEffect(SoundEffectType.BALL_HITS_BALL);
                }
            }
        }

        public override Vector3 GetCollisionPoint()
        {
            Ball ball1 = (Ball)a;
            Ball ball2 = (Ball)b;

            Vector3 tmp = (b.getPosition() + a.getPosition()) / 2;
            return tmp;
            //return b.getPosition();
        }


    }
}
